<template>
	<view class="container">
		<view class="iconEdit animated-item" style="animation-delay: 0.1s">
			<u-icon name="edit-pen" size="30" @click="post"></u-icon>
		</view>

		<!-- 帖子列表 -->
		<view 
			class="content animated-item" 
			v-for="(item, index) in postList" 
			:key="index"
			:style="{animationDelay: `${0.2 + index*0.1}s`}"
		>
			<view class="top">
				<u-avatar :src="baseUrl+item.userAvatar" size="36" class="navbar-avatar"
					style="margin-right: 5px;"></u-avatar>
				<view class="header">
					<view class="tixt">
						<text class="title">{{item.nickName}}</text>
						<text class="time-text">{{item.createTime}}</text>
					</view>
				</view>
			</view>

			<!-- 内容容器 -->
			<view class="content-box">
				<!-- 正文内容 -->
				<view class="content-section">
					<rich-text class="content-text" :nodes="formatRichText(item.content)"></rich-text>
					<u-album :urls="item.images" multipleSize="100"></u-album>
				</view>

				<!-- 底部操作栏 -->
				<view class="bottom-action-bar">
					<view class="stats">
						<!-- 点赞 -->
						<view class="stat-item" @click="handleLike(item)">
							<u-icon :name="item.isLiked ? 'thumb-up-fill' : 'thumb-up'" size="30"
								:color="item.isLiked ? '#2979ff' : '#666666'"></u-icon>
							<text>{{ item.likeCount }}</text>
						</view>

						<!-- 评论 -->
						<view class="stat-item" @click="handleComment(item)">
							<u-icon name="chat" size="30" color="#666666"></u-icon>
						</view>

						<!-- 分享 -->
						<view class="stat-item" @click="handleShare(item)">
							<u-icon name="share" size="30" color="#666666"></u-icon>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 评论弹窗 -->
		<u-popup :show="showComment" mode="bottom" @close="showComment = false">
			<view class="comment-popup animated-item" style="animation-delay: 0.1s">
				<view class="comment-header">
					<text class="comment-title">评论</text>
					<u-icon name="close" @click="showComment = false"></u-icon>
				</view>

				<scroll-view scroll-y="true" class="comment-list">
					<view 
						class="comment-item animated-item" 
						v-for="(comment, cIndex) in currentComments" 
						:key="cIndex"
						:style="{animationDelay: `${0.2 + cIndex*0.1}s`}"
					>
						<u-avatar :src="baseUrl+comment.avatar" size="36"></u-avatar>
						<view class="comment-content">
							<text class="comment-user">{{comment.createBy}}</text>
							<text class="comment-text">{{comment.content}}</text>
							<text class="comment-time">{{comment.createTime}}</text>
						</view>
					</view>

					<u-loadmore :status="commentLoadStatus" v-if="currentComments.length > 0" />
				</scroll-view>

				<view class="comment-input animated-item" style="animation-delay: 0.3s">
					<u-input placeholder="请输入评论内容" v-model="commentContent" border="none" clearable></u-input>
					<u-button type="primary" size="small" @click="submitComment"
						:disabled="!commentContent.trim()">发送</u-button>
				</view>
			</view>
		</u-popup>

		<!-- 加载更多 -->
		<u-loadmore :status="loadStatus" v-if="postList.length > 0" />

		<!-- 空状态 -->
		<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png"
			v-if="postList.length === 0 && !loading" class="animated-item" style="animation-delay: 0.2s">
		</u-empty>
	</view>
</template>

<script>
	import storage from '@/utils/storage'
	import {
		listPost,
		likePost,
		cancelLike,
		listComment,
		addComment,
		sharePost
	} from '@/api/bbs/post'
	import config from '@/config'
	export default {
		data() {
			return {
				baseUrl: config.baseUrl,
				postList: [],
				loading: false,
				loadStatus: 'loadmore',
				pageNum: 1,
				pageSize: 50,
				showComment: false,
				currentPostId: null,
				currentComments: [],
				commentContent: '',
				commentPageNum: 1,
				commentPageSize: 10,
				commentLoadStatus: 'loadmore',
				shareInfo: {
					title: '',
					path: '',
					imageUrl: ''
				}
			}
		},
		onLoad() {
			const nick = storage.get('nickName')
			this.getPostList()
		},
		onReachBottom() {
			if (this.loadStatus === 'nomore') return
			this.pageNum++
			this.getPostList()
		},
		methods: {
			formatRichText(html) {
				return html
					.replace(/<img/gi, '<img style="max-width:100%;height:auto"')
					.replace(/<p/gi, '<p style="margin:0 0 1em 0"');
			},
			async getPostList() {
				this.loadStatus = 'loading'
				try {
					const params = {
						pageNum: this.pageNum,
						pageSize: this.pageSize
					}
					const res = await listPost(params)
					if (res.code === 200) {
						const newList = res.rows.map(item => ({
							...item,
							images: item.images.map(item => {
								return `http://localhost:8080${item.imageUrl}`
							})
						}))
						if (this.pageNum === 1) {
							this.postList = newList
						} else {
							this.postList = [...this.postList, ...newList]
						}
						this.loadStatus = res.rows.length < this.pageSize ? 'nomore' : 'loadmore'
					}
				} catch (err) {
					this.loadStatus = 'loadmore'
					uni.showToast({
						title: '获取帖子列表失败',
						icon: 'none'
					})
				}
			},
			async handleLike(item) {
				try {
					let res;
					if (item.isLiked) {
						res = await cancelLike(item.id);
					} else {
						res = await likePost(item.id);
					}
					if (res.code === 200) {
						item.isLiked = !item.isLiked;
						item.likeCount = item.isLiked ? item.likeCount + 1 : item.likeCount - 1;
					}
				} catch (err) {
					uni.showToast({
						title: err.message || '操作失败',
						icon: 'none'
					});
				}
			},
			async handleComment(item) {
				this.currentPostId = item.id
				this.commentPageNum = 1
				this.commentLoadStatus = 'loading'
				try {
					const params = {
						postId: item.id || this.currentPostId,
						pageNum: this.commentPageNum,
						pageSize: this.commentPageSize
					}
					const res = await listComment(params)
					if (res.code === 200) {
						this.currentComments = res.rows
						this.commentLoadStatus = res.rows.length < this.commentPageSize ? 'nomore' : 'loadmore'
						this.showComment = true
					}
				} catch (err) {
					console.error('获取评论失败:', err)
					uni.showToast({
						title: '获取评论失败',
						icon: 'none'
					})
				}
			},
			async loadMoreComments() {
				if (this.commentLoadStatus === 'nomore') return
				this.commentPageNum++
				this.commentLoadStatus = 'loading'
				try {
					const params = {
						postId: this.currentPostId,
						pageNum: this.commentPageNum,
						pageSize: this.commentPageSize
					}
					const res = await listComment(params)
					if (res.code === 200) {
						this.currentComments = [...this.currentComments, ...res.rows]
						this.commentLoadStatus = res.rows.length < this.commentPageSize ? 'nomore' : 'loadmore'
					}
				} catch (err) {
					console.error('加载更多评论失败:', err)
					this.commentPageNum--
					this.commentLoadStatus = 'loadmore'
				}
			},
			async submitComment() {
				if (!this.commentContent.trim()) {
					uni.showToast({
						title: '评论内容不能为空',
						icon: 'none'
					})
					return
				}
				try {
					const data = {
						postId: this.currentPostId,
						content: this.commentContent,
						createBy: this.$store.state.user.nickName
					}
					const res = await addComment(data)
					if (res.code === 200) {
						const post = this.postList.find(item => item.id === this.currentPostId)
						if (post) {
							post.commentCount += 1
						}
						this.commentContent = ''
						this.commentPageNum = 1
						this.commentLoadStatus = 'loading'
						const params = {
							postId: this.currentPostId,
							pageNum: this.commentPageNum,
							pageSize: this.commentPageSize
						}
						const refreshRes = await listComment(params)
						if (refreshRes.code === 200) {
							this.currentComments = refreshRes.rows
							this.commentLoadStatus = refreshRes.rows.length < this.commentPageSize ? 'nomore' : 'loadmore'
						}
						uni.showToast({
							title: '评论成功',
							icon: 'none'
						})
					}
				} catch (err) {
					console.error('评论失败:', err)
					uni.showToast({
						title: '评论失败',
						icon: 'none'
					})
				}
			},
			async handleShare(item) {
				try {
					const res = await sharePost(item.id)
					if (res.code === 200) {
						item.shareCount += 1
						uni.share({
							provider: 'weixin',
							type: 0,
							title: item.content.length > 20 ? item.content.substring(0, 20) + '...' : item.content,
							summary: '发现有趣的内容，快来看看吧',
							href: `${config.baseUrl}/#/pages/bbs/post/detail?id=${item.id}`,
							imageUrl: item.images && item.images.length > 0 ? item.images[0] : '',
							success: () => {
								uni.showToast({
									title: '分享成功',
									icon: 'none'
								})
							},
							fail: (err) => {
								console.error('分享失败:', err)
							}
						})
					}
				} catch (err) {
					console.error('更新分享数失败:', err)
				}
			},
			post() {
				uni.navigateTo({
					url: '/pages/circle/post'
				})
			}
		},
		onShareAppMessage(res) {
			if (res.from === 'button') {
				const item = this.postList.find(post => post.id === res.target.dataset.id)
				return {
					title: item.content.length > 20 ? item.content.substring(0, 20) + '...' : item.content,
					path: `/pages/bbs/post/detail?id=${item.id}`,
					imageUrl: item.images && item.images.length > 0 ? item.images[0] : ''
				}
			}
			return {
				title: '发现有趣的内容，快来看看吧',
				path: '/pages/bbs/post/index'
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background: #fff;
		padding: 15px;
		font-size: 14px;
		min-height: 100vh;

		.iconEdit {
			display: flex;
			justify-content: flex-end;
			margin-bottom: 15px;
		}

		.content {
			margin-bottom: 15px;
			padding: 15px;
			border-radius: 8px;
			background-color: #fff;
			box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
		}

		.top {
			display: flex;
			align-items: center;
			.header {
				flex: 1;
				padding-left: 10px;
				.tixt {
					display: flex;
					flex-direction: column;
					.title {
						font-size: 16px;
						font-weight: bold;
						color: #333;
					}
					.time-text {
						color: #999;
						font-size: 12px;
						margin-top: 2px;
					}
				}
			}
		}

		.content-box {
			margin-top: 10px;
			.content-section {
				.content-text {
					padding: 5px 0;
					display: block;
					margin-bottom: 10px;
					color: #333;
					line-height: 1.6;
				}
				.u-album {
					margin-top: 10px;
				}
			}
			.bottom-action-bar {
				margin-top: 15px;
				padding-top: 10px;
				border-top: 1px solid #f0f0f0;
				.stats {
					display: flex;
					justify-content: space-around;
					font-size: 14px;
					.stat-item {
						display: flex;
						align-items: center;
						color: #666;
						text {
							margin-left: 5px;
						}
					}
				}
			}
		}
	}

	.comment-popup {
		padding: 20px;
		height: 70vh;
		display: flex;
		flex-direction: column;
		background-color: #fff;
		.comment-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15px;
			padding-bottom: 10px;
			border-bottom: 1px solid #f0f0f0;
			.comment-title {
				font-size: 18px;
				font-weight: bold;
				color: #333;
			}
		}
		.comment-list {
			flex: 1;
			overflow-y: auto;
			margin-bottom: 15px;
			.comment-item {
				display: flex;
				padding: 10px 0;
				border-bottom: 1px solid #f5f5f5;
				.comment-content {
					flex: 1;
					margin-left: 10px;
					display: flex;
					flex-direction: column;
					.comment-user {
						font-weight: bold;
						color: #333;
						margin-bottom: 2px;
					}
					.comment-text {
						color: #333;
						margin-bottom: 2px;
						line-height: 1.5;
					}
					.comment-time {
						color: #999;
						font-size: 12px;
					}
				}
			}
		}
		.comment-input {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			padding: 10px 0;
			border-top: 1px solid #f0f0f0;
			.u-input {
				flex: 1;
				background-color: #f5f5f5;
				border-radius: 18px;
				width: 100%;
				margin: 15rpx 0;
			}
		}
	}

	/* 新增动画样式 */
	.animated-item {
		opacity: 0;
		animation: fadeInUp 0.6s ease forwards;
	}

	@keyframes fadeInUp {
		from {
			opacity: 0;
			transform: translateY(20px);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}
</style>